package com.kylewang.pomodoro.ui.plan;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.kylewang.pomodoro.R;
import com.kylewang.pomodoro.model.TaskModel;
import com.kylewang.pomodoro.helper.DBManager;
import com.kylewang.pomodoro.ui.timer.TimerScene;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

public class TaskAdapter extends BaseAdapter implements Observer {

    private Context mContext;
    private LayoutInflater mInflator;
    private ArrayList<TaskModel> tasks;
    private FirebaseUser user;

    public TaskAdapter(Context c) {
        mContext = c;
        mInflator = (LayoutInflater)
                mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        tasks = new ArrayList<>();
        user = FirebaseAuth.getInstance().getCurrentUser();
        fetchTasks();
    }

    public ArrayList<TaskModel> getTasks() {
        return tasks;
    }

    public void addNewTask(String name) {
        if (user == null) {
            return;
        }
        DBManager.addNewTask(name, user.getUid(), new DBManager.DBApiCallBack<TaskModel>() {
            @Override
            public void onResponse(ArrayList<TaskModel> models) {
                tasks.addAll(models);
                Toast.makeText(mContext, "Add new task success", Toast.LENGTH_LONG).show();
                notifyDataSetChanged();
            }

            @Override
            public void onError(Exception error) {
                Toast.makeText(mContext, "Failed to add a task", Toast.LENGTH_LONG).show();
            }
        });
    }

    public void fetchTasks() {
        if (user == null) {
            return;
        }
        DBManager.fetchTasks(user.getUid(), new DBManager.DBApiCallBack<TaskModel>() {
            @Override
            public void onResponse(ArrayList<TaskModel> models) {
                clearTasks();
                tasks = models;
                notifyDataSetChanged();
            }

            @Override
            public void onError(Exception error) {

            }
        });
    }

    public void clearTasks() {
        tasks.clear();
    }


    @Override
    public int getCount() {

        return getTasks().size();
    }

    @Override
    public Object getItem(int position) { return position; }

    @Override
    public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup
            parent)
    {
        Button btn;
        ImageView starIcon;

        if(convertView == null) {
            convertView = mInflator.inflate(R.layout.task_item,
                    parent,false);
        }

        TaskModel item = getTasks().get(position);
        btn = convertView.findViewById(R.id.toggleButton);
        TextView taskname = convertView.findViewById(R.id.taskname);
        taskname.setText(item.getName());

        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (item.getStatus() == 2) {
                    return;
                }
                TimerScene.TaskItemClickedEvent newEvent = new TimerScene.TaskItemClickedEvent();
                newEvent.item = item;
                EventBus.getDefault().post(newEvent);
            }
        });

        toggleCheckImage(item,btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (item.getStatus() != 2) {
                    // Mark to finish status
                    item.setStatus(2);
                    item.setElapsed_duration(item.getTarget_time());
                    toggleCheckImage(item,btn);

                } else {
                    item.setStatus(0);
                    item.setElapsed_duration(0);
                    toggleCheckImage(item,btn);
                }
                DBManager.updateTask(item);
            }
        });

        starIcon = convertView.findViewById(R.id.imageView2);
        toggleStarImage(item, starIcon);
        starIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                item.setCollected(!item.isCollected());
                toggleStarImage(item,starIcon);
                DBManager.updateTask(item);
            }
        });

        return convertView;
    }

    public void toggleStarImage(TaskModel item, ImageView view) {
        view.setImageDrawable(mContext.getResources().getDrawable(item.isCollected() ? R.drawable.star_fill : R.drawable.star));
    }

    public void toggleCheckImage(TaskModel item, Button btn) {
        btn.setCompoundDrawablesWithIntrinsicBounds(item.getStatus() == 2 ? R.drawable.item_selected : R.drawable.item_normal,0,0,0);
    }

    @Override
    public void update(Observable observable, Object o) {
        clearTasks();
        if (o instanceof FirebaseUser) {
            user = (FirebaseUser)o;
            fetchTasks();
        } else {
            user = null;
            notifyDataSetChanged();
        }
    }
}
